// ShortPosLimitDlg.cpp : implementation file
//

#include "stdafx.h"
#include "LightspeedTraderAPIDemo.h"
#include "ShortPosLimitDlg.h"


// ShortPosLimitDlg dialog

IMPLEMENT_DYNAMIC(ShortPosLimitDlg, CModelessDialog)

ShortPosLimitDlg::ShortPosLimitDlg(CWnd* pParent /*=NULL*/)
	: CModelessDialog(ShortPosLimitDlg::IDD, pParent)
	, m_ShortLimitsListCtrl(CListCtrl())
	, account(NULL)
{

}

ShortPosLimitDlg::~ShortPosLimitDlg()
{
	if (account)
	{
		account->L_Detach(this);
		account = NULL;
	}
}

BOOL ShortPosLimitDlg::Create(CWnd *pParentWnd /*= CWnd::FromHandle(L_GetMainWnd())*/)
{
	return __super::Create(ShortPosLimitDlg::IDD, pParentWnd);
}

BOOL ShortPosLimitDlg::OnInitDialog()
{
	__super::OnInitDialog();

	DWORD style = m_ShortLimitsListCtrl.GetExtendedStyle();
	style |= LVS_EX_FULLROWSELECT;
	style |= LVS_EX_GRIDLINES;
	style |= LVS_EX_DOUBLEBUFFER;
	m_ShortLimitsListCtrl.SetExtendedStyle(style);

	m_ShortLimitsListCtrl.InsertColumn(0, "Symbol", LVCFMT_LEFT, 110);
	m_ShortLimitsListCtrl.InsertColumn(1, "Short Limit", LVCFMT_RIGHT, 110);

	account = L_GetAccount();
	account->L_Attach(this);

	UpdateShortLimitList();

	return TRUE;
}

void ShortPosLimitDlg::DoDataExchange(CDataExchange* pDX)
{
	__super::DoDataExchange(pDX);

	DDX_Control(pDX, IDC_SHORTLIMITLIST, m_ShortLimitsListCtrl);
}

void ShortPosLimitDlg::UpdateShortLimitList()
{
	CString shortLimitTxt;
	int row = 0;
	for (locate_symbol_iterator it(account->locate_symbols_begin()), itend(account->locate_symbols_end());
		it != itend; ++it, ++row)
	{
		if (row >= m_ShortLimitsListCtrl.GetItemCount())
		{
			m_ShortLimitsListCtrl.InsertItem(row, *it);
		}
		else
		{
			m_ShortLimitsListCtrl.SetItemText(row, 0, *it);
		}

		shortLimitTxt.Format("%d", account->L_GetShortPositionLimit(*it));
		m_ShortLimitsListCtrl.SetItemText(row, 1, shortLimitTxt);
	}

	while (row < m_ShortLimitsListCtrl.GetItemCount())
	{
		m_ShortLimitsListCtrl.DeleteItem(row);
	}
}

//L_Observer
void ShortPosLimitDlg::HandleMessage(L_Message const *pMsg)
{
	switch (pMsg->L_Type())
	{
	case L_MsgShortLimitChange::id:
		{
			UpdateShortLimitList();
		}
		break;
	}
}

BEGIN_MESSAGE_MAP(ShortPosLimitDlg, CModelessDialog)
	ON_WM_SIZE()
END_MESSAGE_MAP()


// ShortPosLimitDlg message handlers

void ShortPosLimitDlg::OnSize(UINT nType, int cx, int cy)
{
	__super::OnSize(nType, cx, cx);

	ResizeControls();
}

void ShortPosLimitDlg::ResizeControls()
{
	if (m_hWnd && m_ShortLimitsListCtrl.m_hWnd)
	{
		RECT rect;
		GetClientRect(&rect);

		RECT sizeLimitRect;
		m_ShortLimitsListCtrl.GetWindowRect(&sizeLimitRect);
		ScreenToClient(&sizeLimitRect);

		rect.top = sizeLimitRect.top;

		m_ShortLimitsListCtrl.MoveWindow(&rect);
	}
}